export default {
    // 替换全部
    replaceAll(str, s1, s2) {
        return str.replace(new RegExp(s1, "gm"), s2);
    },

    //区间随机整数(1000,9999)
    random(n, m) {
        return Math.floor(Math.random() * (m - n + 1) + n);
    },

    // 过滤所有特殊字符
    stripScript(s) {
        let pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？↵\r\n]");
        let rs = "";
        for (let i = 0; i < s.length; i++) {
            rs = rs + s.substr(i, 1).replace(pattern, '');
        }
        return rs;
    },

    // 把数组差分成多个数组
    groupArray(array, subGroupLength) {
        let index = 0;
        let newArray = [];
        while (index < array.length) {
            newArray.push(array.slice(index, index += subGroupLength));
        }
        return newArray;
    },

    //获得角度
    getAngle(angx, angy) {
        return Math.atan2(angy, angx) * 180 / Math.PI;
    },

    //根据起点终点返回方向 1向上 2向下 3向左 4向右 0未滑动
    getDirection(startx, starty, endx, endy) {
        var angx = endx - startx;
        var angy = endy - starty;
        var result = 0;

        //如果滑动距离太短
        if (Math.abs(angx) < 2 && Math.abs(angy) < 2) {
            return result;
        }

        var angle = this.getAngle(angx, angy);
        if (angle >= -135 && angle <= -45) {
            result = 1;
        } else if (angle > 45 && angle < 135) {
            result = 2;
        } else if ((angle >= 135 && angle <= 180) || (angle >= -180 && angle < -135)) {
            result = 3;
        } else if (angle >= -45 && angle <= 45) {
            result = 4;
        }

        return result;
    },

    //日期格式化
    dateFormat(inputDate, fmt) {
        let date;
        if (typeof inputDate == 'object') {
            date = inputDate;
        } else if (typeof inputDate == 'number') {
            date = inputDate.toString().length == 10 ? new Date(inputDate * 1000) : new Date(inputDate);
        } else if (typeof inputDate == 'string') {
            date = new Date(inputDate.replace(/-/g, '\/'));
        }
        let o = {
            "M+": date.getMonth() + 1,
            "d+": date.getDate(),
            "h+": date.getHours(),
            "m+": date.getMinutes(),
            "s+": date.getSeconds(),
            "q+": Math.floor((date.getMonth() + 3) / 3),
            "S": date.getMilliseconds()
        };

        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (let k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }
        return fmt;
    },

    // 时间差=>小时
    timeDiff(time) {
        let time_diff = new Date().getTime() - time; //时间差的毫秒数
        //计算出相差天数
        let days = Math.floor(time_diff / (24 * 3600 * 1000));
        //计算出小时数
        let leave1 = time_diff % (24 * 3600 * 1000);
        let hours = Math.floor(leave1 / (3600 * 1000));
        //计算相差分钟数
        let leave2 = leave1 % (3600 * 1000);
        let minutes = Math.floor(leave2 / (60 * 1000));
        //计算相差秒数
        let leave3 = leave2 % (60 * 1000);
        let seconds = Math.round(leave3 / 1000);
        // console.log([days,hours,minutes,seconds])

        return days * 24 + hours
    },

    // 能后退带指定URL
    canBack(url,callback) {
        let goBack = function () {
            if(callback){
                callback && callback()
            } else {
                window.location.replace(url)
            }
        }
        if (window.history && window.history.pushState) {
            history.pushState(null, null, document.URL)
            window.addEventListener('popstate', goBack, false)
        } else {
            window.removeEventListener('popstate', goBack, false)
        }
    },

    // 不能后退
    noBack() {
        history.pushState(null, null, document.URL)
        window.addEventListener('popstate', function () {
            history.pushState(null, null, document.URL)
        })
    },

    // 能前进
    canForward() {
        window.addEventListener('popstate', function (e) {
            if (e.state) {
                window.location = e.state.url
            }
        }, false)
    },

    // 禁止右键菜单
    onContextMenu(event) {
        if (this.isIOS() || this.isAndroid()) {
            event.preventDefault()
        }
    },

    // 参数转化
    covertParams(str) {
        let params = {}
        let arr = str.split('&')
        arr.forEach(item => {
            let s = item.split('=')
            params[s[0]] = s[1]
        })
        return params
    },

    //获取查询参数
    queryString(name) {
        let arr = window.location.href.split('?');
        if(arr.length>1){
            let query = arr[1];
            let vars = query.split('&');
            for (let i = 0; i < vars.length; i++) {
                let pair = vars[i].split("=");
                if (pair[0] == name) {
                    return pair[1];
                }
            }
        }
        return (false);
    },
    
    //获取元素是否在可视区域
    isViewport(el, val, index) {
        let h = el.offsetHeight
        let rect = el.getBoundingClientRect();
        if (val.scrollTop === 0) {
            if (index == 0) {
                return true
            }
            return false;
        }
        if (index == 1 && val.scrollTop < h / 3) {
            return false
        }
        return (
            rect.top >= 0 &&
            rect.top <=
            (window.innerHeight || document.documentElement.clientHeight) - h / 10 &&
            rect.left >= 0 &&
            rect.bottom <=
            (window.innerHeight || document.documentElement.clientHeight) + h / 10 &&
            rect.right <=
            (window.innerWidth || document.documentElement.clientWidth)
        );
    },

    // 模拟点击
    clickEvent(el) {
        let e = document.createEvent("MouseEvents");
        e.initEvent("click", true, true);
        el.dispatchEvent(e);
        el.focus();
    }
}